#include "client.h"
#include "ui_client.h"
#include "server_file.h"
#include "client_file.h"
Client::Client(QString serverIP, QString serverID,QString myID, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Client)
{
    this->setWindowTitle(serverIP);
    ui->setupUi(this);
    setWindowTitle("Client");
    this->serverIP =serverIP;
    this->serverID =serverID;
    this->myID =myID;
    tcpSocket= new QTcpSocket(this);
    tcpSocket->connectToHost(serverIP,(quint16)6020);
    connect(tcpSocket,&QTcpSocket::connected, this, &Client::connected_Slot);
    connect(ui->sendButton, &QPushButton::clicked, this, &Client::on_sendButton_clicked);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &Client::on_disconnected);
}

void Client::connected_Slot()   //连接槽函数
{
    ui->recvEdit->append("连接用户" + this->serverID + "(IP:" + this->serverIP + ")" + "成功！");
    connect(tcpSocket,&QTcpSocket::readyRead,this,&Client::readyRead_Slot);

}

void Client::readyRead_Slot()    //读取数据槽函数
{
    QByteArray msg_array =QByteArray(1000,0);

    msg_array = tcpSocket->readAll();
    QDataStream stream(&msg_array,QIODevice::ReadOnly);
    ui->recvEdit->setTextColor(QColor(Qt::blue));
    QString name, msg;
    stream >> name >> msg;
    ui->recvEdit->append(name + ":" + msg);
}


Client::~Client()
{
    // 确保在析构时断开连接
    if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        qDebug() << "Disconnecting from host...";
        tcpSocket->disconnectFromHost();
        if (tcpSocket->state() != QAbstractSocket::UnconnectedState)
        {
            // 等待断开
            tcpSocket->waitForDisconnected(3000); // 3秒超时
        }
    }
    delete tcpSocket;
    delete ui;
}

//处理对方断开连接
void Client::on_disconnected()
{
    ui->recvEdit->append("对方已断开连接！");
    delete tcpSocket;
}

void Client::on_sendButton_clicked()    //发送按钮按下
{
    ui->recvEdit->setTextColor(QColor(210,105,30));
    QByteArray buf;
    QDataStream stream(&buf, QIODevice::WriteOnly);
    QString text = ui->sendEdit->toPlainText();
    if(!text.isEmpty())
    {
        stream<< this->myID << text;

        if(tcpSocket)
        {
            tcpSocket->write(buf);
        }
        else
        {
            QMessageBox::warning(this, "警告", "发送失败！已断开连接");
        }
        qDebug() << "Sending message:" << ui->sendEdit->toPlainText();
        ui->recvEdit->append("我：" + ui->sendEdit->toPlainText());
        ui->sendEdit->clear();
    }
}


void Client::on_SendFileButton_clicked()
{
    server_file * a= new server_file;
    a->show();
}


void Client::on_recvButton_clicked()
{
    client_file *a = new client_file(0,this->serverIP);
    a->show();
}



